import bcrypt
import secrets
import logging
from typing import Tuple

logger = logging.getLogger(__name__)

class PasswordManager:
    """安全的密码管理类，使用bcrypt进行密码哈希"""
    
    @staticmethod
    def hash_password(password: str) -> Tuple[str, str]:
        """
        使用bcrypt哈希密码
        
        Args:
            password: 明文密码
            
        Returns:
            Tuple[哈希密码, 盐]
        """
        if not password:
            raise ValueError("密码不能为空")
            
        # 生成盐并使用bcrypt哈希密码
        salt = bcrypt.gensalt()
        hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
        
        logger.info("密码哈希成功")
        return hashed.decode('utf-8'), salt.decode('utf-8')
    
    @staticmethod
    def verify_password(password: str, hashed_password: str) -> bool:
        """
        验证密码是否正确
        
        Args:
            password: 明文密码
            hashed_password: 哈希后的密码
            
        Returns:
            bool: 密码是否正确
        """
        if not password or not hashed_password:
            return False
            
        try:
            result = bcrypt.checkpw(
                password.encode('utf-8'), 
                hashed_password.encode('utf-8')
            )
            logger.info("密码验证完成")
            return result
        except Exception as e:
            logger.error(f"密码验证失败: {e}")
            return False
    
    @staticmethod
    def generate_secure_token(length: int = 32) -> str:
        """
        生成安全的随机令牌
        
        Args:
            length: 令牌长度
            
        Returns:
            str: 安全令牌
        """
        return secrets.token_hex(length)